package com.liuxing.doctor.controller;

import com.liuxing.doctor.dto.*;
import com.liuxing.doctor.entity.Doctor;
import com.liuxing.doctor.entity.MedicalRecord;
import com.liuxing.doctor.entity.Patient;
import com.liuxing.doctor.entity.Prescription;
import com.liuxing.doctor.service.MedicalRecordService;
import com.liuxing.doctor.service.PatientService;
import com.liuxing.doctor.service.PrescriptionService;
import com.liuxing.doctor.service.impl.DoctorServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 行柳
 * 学习使用
 */
@Controller
@RequestMapping("/xmlParse")
public class XmlParseOfDoctorController {
    @Resource
    private PatientService patientService;
    @Resource
    private MedicalRecordService medicalRecordService;
    @Resource
    private PrescriptionService prescriptionService;
    @Resource
    private DoctorServiceImpl doctorService;
    @RequestMapping(value = "/index")
    public String index(){
        return "1";
    }
    @RequestMapping(value = "/upload")
    public void upload(@RequestParam("file") MultipartFile file,HttpServletResponse response,HttpServletRequest request) throws Exception{
            JAXBContext jaxbContext=JAXBContext.newInstance(PatientInfoDtos.class);
            Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
            PatientInfoDtos patientInfoDtos= (PatientInfoDtos) unmarshaller.unmarshal(file.getInputStream());
            List<PatientInfoDto> patientInfoDtoList=patientInfoDtos.getPatientInfoDtoList();

            for (PatientInfoDto patientInfoDto : patientInfoDtoList) {
                //得到patient并插入
                patientService.insertOnePatient(patientInfoDto.getPatient());
                List<MedicalRecord> medicalRecordList=patientInfoDto.getMedicalRecords().getMedicalRecordList();
                List<Prescription> prescriptionList=patientInfoDto.getPatientPrescriptions().getPrescriptionList();
                for (MedicalRecord medicalRecord : medicalRecordList){
                   medicalRecordService.insertMedicalRecord(medicalRecord);
                }
                for (Prescription prescription : prescriptionList){
                    prescriptionService.insertPrescription(prescription);
                }
            }
        response.sendRedirect(request.getRequestURL().substring(0,16)+":"+request.getServerPort()+"/"+"main/index");
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET,produces = "application/xml")
    @ResponseBody
    public ResponseEntity<byte[]> download(HttpServletResponse response, HttpServletRequest request){
        try {
            List<Doctor> doctorList=doctorService.selectAll();
            Doctors doctors=new Doctors();
            doctors.setDoctors(doctorList);
            //拿到patientInfoDtos作为根节点
            PatientInfoDtos patientInfoDtos=new PatientInfoDtos();
            //patientInfoDtos存放的时PatientInfoDtod的集合
            List<PatientInfoDto> patientInfoDtoList=new ArrayList<PatientInfoDto>();

            //以下循环拿到每一个PatientInfoDto
            List<Patient> patientList=patientService.queryAllPatientWithMedicalRecordIdNotNull();
            for (Patient patient : patientList
                 ) {
                //PatientInfoDtos节点下的一个根节点 --PatientInfoDto
                PatientInfoDto patientInfoDto=new PatientInfoDto();
                //PatientInfoDto节点里面的内容 --patient
                patientInfoDto.setPatient(patient);

                //PatientInfoDto节点下的一个根节点 --MedicalRecords
                MedicalRecords medicalRecords=new MedicalRecords();
                //MedicalRecords节点里面的内容medicalRecordList
                List<MedicalRecord> medicalRecordList=medicalRecordService.queryByPatientId(patient.getPatientId());
                medicalRecords.setMedicalRecordList(medicalRecordList);

                //PatientInfoDto节点下的一个根节点 --PatientPrescriptions
                PatientPrescriptions patientPrescriptions=new PatientPrescriptions();
                //PatientPrescriptions节点里面的内容prescriptionList
                List<Prescription> prescriptionList=prescriptionService.queryPrescriptionsByPatientId(patient.getPatientId());
                patientPrescriptions.setPrescriptionList(prescriptionList);

                //将MedicalRecords节点放入PatientInfoDto节点
                patientInfoDto.setMedicalRecords(medicalRecords);
                //将PatientPrescriptions节点放入PatientInfoDto节点
                patientInfoDto.setPatientPrescriptions(patientPrescriptions);

                patientInfoDtoList.add(patientInfoDto);
            }
            patientInfoDtos.setPatientInfoDtoList(patientInfoDtoList);

            JAXBContext jaxbContext=JAXBContext.newInstance(PatientInfoDtos.class);
            Marshaller marshaller=jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(patientInfoDtos, writer);
            String writerStr=writer.toString();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "patientInfoDtos.xml");
            headers.setContentLength(writerStr.getBytes().length);
            headers.setContentLength(writerStr.getBytes(StandardCharsets.UTF_8).length);
            writer.close();
            return new ResponseEntity<>(writerStr.getBytes(),headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
